#!/usr/bin/env python
#coding=utf-8
#一个多线程socket测试客户端

import sys, socket, time, os
import threading

#工作线程函数
def workthread(host,port,sendnumbers,sleeptime):
    ths = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ths.connect((host, port))
    while sendnumbers:
        buffer="SEND %d" % sendnumbers
        ths.send(buffer)
        #print buffer
        sendnumbers -= 1
        time.sleep(sleeptime)
    ths.close()
    print 'thread done'

#检测活动线程
def checkalivethread(threads):
    #枚举alive线程id
    thidnume=[str(x.ident) for x in threading.enumerate()]
    #循环判断，如果某个线程已经不在活动线程列表中，则从字典中删除该项。
    for key,value in threads.items():
        if key not in thidnume:
            threads.pop(key)
    outputinfo='current alive thread:%s' % str([key for key,value in threads.items()])
    print outputinfo
    #返回活动线程数量
    return len(threads)

def main():
    HOST = '192.168.171.128'
    PORT = 12345
    
    threads={}
    #停止程序运行的文件名
    stopfile='stop'
    #每个线程发送几次数据
    sendnumbers=10
    #总共启动多少个测试线程
    testthreadnumbers=5
    #每个线程每发送一次数据休息多少时间（秒）
    sleeptime=1

    #通过在程序运行目录下创建stop文件来停止该程序运行。
    if os.path.isfile(stopfile):
        outputinfo='stopfile:%s is exist,begin to exit...' % stopfile
        print outputinfo
        return 0

    #循环启动线程
    for i in range(testthreadnumbers):
        th=threading.Thread(target=workthread,name='workthread',args=(HOST,PORT,sendnumbers,sleeptime))
        th.start()
        #线程id
        thid=str(th.ident)
        threads[thid]=th    
    
    while 1:
        #通过在程序运行目录下创建stop文件来停止该程序运行。
        if os.path.isfile(stopfile):
            outputinfo='stopfile:%s is exist,begin to exit...' % stopfile
            print outputinfo
            break
        
        #检测活动线程
        ret=checkalivethread(threads)

        #控制启动多少线程来测试
        if len(threads)>=testthreadnumbers:
            time.sleep(1)
            continue
        
        print 'begin to start new thread'
        th=threading.Thread(target=workthread,name='workthread',args=(HOST,PORT,sendnumbers,sleeptime))
        th.start()
        #线程id
        thid=str(th.ident)
        threads[thid]=th 
        
        #time.sleep(1)
    
    #等待所有线程结束
    while checkalivethread(threads):
        time.sleep(1)
    return 0

if __name__ == '__main__':
    main()
    print 'main done'
